package com.iflytek.yly.jetpackdemo.room;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.iflytek.yly.jetpackdemo.R;
import com.iflytek.yly.jetpackdemo.livedata.TimerWithLiveDataViewModel;
import com.iflytek.yly.jetpackdemo.utils.ThreadUtils;

import java.util.ArrayList;
import java.util.List;

public class RoomStudentActivity extends AppCompatActivity {

    StudentDao studentDao;

    private List<Student> studentList = new ArrayList<>();
    private StudentAdapter studentAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_student);
        studentDao = MyDatabase.getInstance(this).studentDao();
        initComponent();
    }

    private void initComponent(){

        StudentViewModel studentViewModel = new ViewModelProvider(this)
                .get(StudentViewModel.class);
        studentViewModel.getLiveDataStudent().observe(this, new Observer<List<Student>>() {
            @Override
            public void onChanged(List<Student> students) {
                students.clear();
                students.addAll(students);
                studentAdapter.notifyDataSetChanged();
            }
        });

        findViewById(R.id.tvAddStudent).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        studentDao.insertStudent(new Student("小王","18"));
                    }
                }).start();

            }
        });

        studentAdapter = new StudentAdapter(R.layout.rv_item_student,studentList);
        RecyclerView recyclerView = findViewById(R.id.rvShowStudent);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(studentAdapter);
        new Thread(new Runnable() {
            @Override
            public void run() {
                studentList.addAll(studentDao.getStudentList());
                studentAdapter.notifyDataSetChanged();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        }).start();
    }

}
